package com.nuo.backend.common.excel.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelDateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.extension.service.IService;
import com.nuo.backend.common.excel.constant.Constant;
import com.nuo.backend.common.excel.listener.ExcelListener;
import com.nuo.backend.common.excel.po.ExportListPo;
import com.nuo.backend.common.excel.service.BaseIService;
import com.nuo.backend.common.excel.service.ExcelService;
import com.nuo.backend.common.utils.R;
import com.nuo.backend.config.LocalYml;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @description: TODO 操作 excel 的具体实现类
 * @author nuo
 * @date 2022/11/8 2:33
 * @version 1.0
 */
@Service("excelService")
public class ExcelServiceImpl<T, S extends IService<T> & BaseIService<T>> implements ExcelService<T, S> {

    @Resource
    LocalYml localYml;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R importList(MultipartFile file, Class<T> clazz, S s) {
        String filename = file.getOriginalFilename();
        if (StrUtil.isBlank(filename) || filename.lastIndexOf(".") == -1) {
            return R.error("文件类型错误...");
        }
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
        if (!Constant.XLS.toString().toLowerCase().equals(suffix) && !Constant.XLSX.toString().toLowerCase().equals(suffix)) {
            return R.error("文件类型错误...");
        }
        try {
            EasyExcel.read(file.getInputStream(), clazz, new ExcelListener<>(clazz, s)).sheet().doRead();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    @Override
    public R exportList(ExportListPo<T> po, Class<T> clazz) {
        String fileName = System.currentTimeMillis() + "." + Constant.XLSX.toString().toLowerCase();
        EasyExcel.write(localYml.getUploadAddress() + fileName, clazz)
                .sheet()
                .doWrite(po.getList());
        return R.ok().put("url", localYml.getVisitAddress() + fileName);
    }

    @Override
    public R exportAll(Class<T> clazz, S s) {
        return exportList(new ExportListPo<T>().setList(s.list()), clazz);
    }

}
